package top.archiesean.authorize.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.annotation.web.configurers.RequestCacheConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import top.archiesean.authorize.support.core.FormIdentityLoginConfigurer;
import top.archiesean.authorize.support.core.SeanDaoAuthenticationProvider;


/**
 * @author ArchieSean
 * @description security配置
 * @date 2024-01-06 23:38
 */
@EnableWebSecurity
@Configuration
@RequiredArgsConstructor
public class WebSecurityConfig {

    /**
     * A Spring Security filter chain for authentication.
     *
     * @param http the httpSecurity
     * @return the securityFilterChain
     * @throws Exception the exception
     */
    @Bean
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
            throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                        //不需要鉴权的接口
                        .requestMatchers("/token/**", "/actuator/**")
                        .permitAll()
                        .requestMatchers(HttpMethod.GET, "/css/**",
                                "/js/**", "/img/**").permitAll()
                        .anyRequest().authenticated()
                )
                // 避免iframe页面嵌入
                .headers(header -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
                //禁用session
                .sessionManagement().disable()
                .csrf().disable();

        http.apply(new FormIdentityLoginConfigurer());
        // 处理 UsernamePasswordAuthenticationToken
        http.authenticationProvider(new SeanDaoAuthenticationProvider());
        return http.build();
    }
}
